package com.wuyan.locationdog.util.maputil

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapView
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.MarkerOptions
import com.arcsoft.commonbase.bean.DeviceBeanContent
import com.arcsoft.commonbase.bean.PointBean
import com.arcsoft.commonbase.ext.gone
import com.arcsoft.commonbase.ext.invisible
import com.arcsoft.commonbase.ext.radius
import com.arcsoft.commonbase.ext.visible
import com.arcsoft.commonbase.ext.visibleOrGone
import com.arcsoft.commonbase.ext.visibleOrInvisible
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.SizeUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.wuyan.locationdog.R
import com.wuyan.locationdog.help.DeviceHelp
import com.wuyan.locationdog.help.DogHelp
import com.wuyan.locationdog.help.getKmOrM
import com.wuyan.locationdog.view.MapPopup
import leifu.shapelibrary.ShapeView

object MapHelp {
   var phonelatLng:LatLng?=null
    fun initLocation(context: Context?, mLocationListener: AMapLocationListener?) {
        //初始化AMapLocationClientOption对象
        val mLocationOption = AMapLocationClientOption().apply {
            //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
            //设置定位间隔,单位毫秒,默认为2000ms
            interval = 2000
            isOnceLocation = true
        }
        val mLocationClient = AMapLocationClient(context).apply {
            //设置定位回调监听
            setLocationListener(mLocationListener)
            //给定位客户端对象设置定位参数f
            setLocationOption(mLocationOption)
            //启动定位
            startLocation()
        }
    }


    /**
     *  设置缩放边界自适应
     */
    fun setMapBounds(mapView: MapView, latLngs: MutableList<LatLng>) {
        //设置缩放边界自适应
        val latLngBounds = LatLngBounds.builder()
        for (i in latLngs.indices) {
            latLngBounds.include(latLngs[i])
        }
        mapView.map.animateCamera(
            CameraUpdateFactory.newLatLngBounds(
                latLngBounds.build(),
                SizeUtils.dp2px(50f)
            )
        )//int width, int height, int padding


    }


    fun getMarkerUi(
        layoutInflater: LayoutInflater,
        deviceBeanContent: DeviceBeanContent,
        titleVisible: Boolean = false,
        phonelatLng: LatLng? = null,
        callback: ((MarkerOptions) -> Unit)
    ) {
        val markerView = layoutInflater.inflate(R.layout.custom_info_window, null)

        markerView.apply {
            findViewById<View>(R.id.nameLayout).visibleOrInvisible(titleVisible)
            if (titleVisible) {
                val calculateLineDistance =
                    AMapUtils.calculateLineDistance(phonelatLng, LatLng(deviceBeanContent.gaoDeLat, deviceBeanContent.gaoDeLng));
                findViewById<TextView>(R.id.distance).setText("${getKmOrM(calculateLineDistance.toInt())}")
            }


            findViewById<TextView>(R.id.tvTitle).text = DeviceHelp.getDeviceName(deviceBeanContent)
            val shapeView = findViewById<ShapeView>(R.id.shapeView)
            findViewById<ImageView>(R.id.ivTriangle).apply {
                when (deviceBeanContent.compositeDetailStatus) {
                    1 -> {
                        setImageResource(R.mipmap.mark_driver_3)
                        shapeView.setShapeStrokeColor(Color.parseColor("#2BAD84"))
                            .setShapeSolidColor(Color.parseColor("#FFFFFF"))
                            .setShapeStrokeWidth(1)
                            .setUseShape()
                    }

                    2 -> {
                        setImageResource(R.mipmap.mark_stoping_3)
                        shapeView.setShapeStrokeColor(Color.parseColor("#FF9F18"))
                            .setShapeSolidColor(Color.parseColor("#FFFFFF"))
                            .setShapeStrokeWidth(1)
                            .setUseShape()
                    }

                    3 -> {
                        setImageResource(R.mipmap.mark_alarm_3)
                        shapeView.setShapeStrokeColor(Color.parseColor("#FF3B30"))
                            .setShapeSolidColor(Color.parseColor("#FFFFFF"))
                            .setShapeStrokeWidth(1)
                            .setUseShape()
                    }

                    4 -> {
                        setImageResource(R.mipmap.mark_unline_3)
                        shapeView.setShapeStrokeColor(Color.parseColor("#A5A5A5"))
                            .setShapeSolidColor(Color.parseColor("#FFFFFF"))
                            .setShapeStrokeWidth(1)
                            .setUseShape()
                    }

                    5 -> {
                        setImageResource(R.mipmap.mark_no_use_3)
                        shapeView.setShapeStrokeColor(Color.parseColor("#5AE4D9"))
                            .setShapeSolidColor(Color.parseColor("#FFFFFF"))
                            .setShapeStrokeWidth(1)
                            .setUseShape()
                    }

                    else -> {
                        setImageResource(R.mipmap.mark_expire_3)
                        shapeView.setShapeStrokeColor(Color.parseColor("#666666"))
                            .setShapeSolidColor(Color.parseColor("#FFFFFF"))
                            .setShapeStrokeWidth(1)
                            .setUseShape()
                    }
                }


            }
            findViewById<ImageView>(R.id.compositeDetailStatus).apply {
                //设备复合详细状态(1行驶2静止3报警4离线5未激活6已过期)

                when (deviceBeanContent.compositeDetailStatus) {
                    1 -> {
                        setImageResource(R.mipmap.mark_driver_style2)
                    }

                    2 -> {
                        setImageResource(R.mipmap.mark_stoping_style2)
                    }

                    3 -> {
                        setImageResource(R.mipmap.mark_alarm_style2)
                    }

                    4 -> {
                        setImageResource(R.mipmap.mark_unline_style2)
                    }

                    5 -> {
                        setImageResource(R.mipmap.mark_no_use_style2)
                    }

                    else -> {
                        setImageResource(R.mipmap.mark_expire_style2)
                    }
                }

            }
            val markerOptions = MarkerOptions().position(LatLng(deviceBeanContent.gaoDeLat, deviceBeanContent.gaoDeLng))
                .anchor(0.5f, 1f)
                .icon(BitmapDescriptorFactory.fromView(markerView))
            callback.invoke(markerOptions)

        }
    }


    fun getMarkerPointUi(
        layoutInflater: LayoutInflater,
        mPointBean: PointBean,
        titleVisible: Boolean = false,
        phonelatLng: LatLng?
    ): MarkerOptions {


        val markerView = layoutInflater.inflate(R.layout.custom_mark_marker, null)

        markerView.findViewById<TextView>(R.id.title).setText(mPointBean.pointName)
        val desc = markerView.findViewById<TextView>(R.id.desc)
        val titleParent = markerView.findViewById<View>(R.id.titleParent)
        if (titleVisible) {
            titleParent.visible()
        } else {
            titleParent.invisible()
        }


        markerView.findViewById<TextView>(R.id.btnNav).setOnClickListener {
            MapPopup(ActivityUtils.getTopActivity()).apply {
                showPopupWindow()
                mapClick(mPointBean.pointLat, mPointBean.pointLng)
            }
        }

        val calculateLineDistance = AMapUtils.calculateLineDistance(phonelatLng, LatLng(mPointBean.pointLat, mPointBean.pointLng));
        desc?.setText("距离：${getKmOrM(calculateLineDistance.toInt())}")
        var pointType = mPointBean.pointType
        if (pointType > 0) {
            pointType -= 1
        }
        markerView.findViewById<ImageView>(R.id.pointType).setImageResource(DogHelp.getMarkList()[pointType].img)

        val markerOptions = MarkerOptions().position(LatLng(mPointBean.pointLat, mPointBean.pointLng))
            .anchor(0.5f, 1f)
            .icon(BitmapDescriptorFactory.fromView(markerView))

        return markerOptions
    }
}

fun ImageView.setDeviceHead(deviceBeanContent: DeviceBeanContent, callback: (() -> Unit)? = null) {
    if (!deviceBeanContent.deviceDetailVO.deviceAvatarUrl.isNullOrEmpty()) {
        Glide.with(context).load(deviceBeanContent.deviceDetailVO.deviceAvatarUrl)
            .apply(RequestOptions.bitmapTransform(CircleCrop()))
            .placeholder(R.mipmap.car)
            .error(R.mipmap.car)
            .fallback(R.mipmap.car)
            .into(object : CustomTarget<Drawable>(50, 50) {
                override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                    this@setDeviceHead.setImageDrawable(resource)
                    callback?.invoke()
                }

                override fun onLoadCleared(placeholder: Drawable?) {


                }

                override fun onLoadFailed(errorDrawable: Drawable?) {
                    super.onLoadFailed(errorDrawable)
                    callback?.invoke()
                }
            })
//        loadImageCircleCar(deviceBeanContent.deviceDetailVO.deviceAvatarUrl)
        return
    }
    when (deviceBeanContent.deviceDetailVO.usageType) {
        1 -> {
            setImageResource(R.mipmap.mark_scene_car)
        }

        2 -> {
            setImageResource(R.mipmap.mark_scene_dog)
        }

        3 -> {
            setImageResource(R.mipmap.mark_scene_person)
        }

        4 -> {
            setImageResource(R.mipmap.mark_scene_other)
        }

        5 -> {
            setImageResource(R.mipmap.mark_scene_money)
        }

    }
    callback?.invoke()
}

fun getDeviceHeadResource(usageType: Int): Int {
    return when (usageType) {
        1 -> {
            R.mipmap.mark_scene_car
        }

        2 -> {
            R.mipmap.mark_scene_dog
        }

        3 -> {
            R.mipmap.mark_scene_person
        }

        4 -> {
            R.mipmap.mark_scene_other
        }

        5 -> {
            R.mipmap.mark_scene_money
        }

        else -> {
            R.mipmap.mark_scene_car
        }
    }
}

fun ImageView.setDeviceDetailStatus(compositeDetailStatus: Int) {
    //设备复合详细状态(1行驶2静止3报警4离线5未激活6已过期)
    gone()
    when (compositeDetailStatus) {
        1 -> {
            setImageResource(R.mipmap.status_driver)
        }

        2 -> {
            setImageResource(R.mipmap.status_stoping)
        }

        3 -> {
            setImageResource(R.mipmap.status_alarm)
        }

        4 -> {
            setImageResource(R.mipmap.status_unline)
        }

        5 -> {
            gone()
        }

        else -> {
            gone()
        }

    }

}

fun View.setOvalStatus(deviceBeanContent: DeviceBeanContent) {

    this.radius(SizeUtils.dp2px(3F).toFloat())
    when (deviceBeanContent.compositeDetailStatus) {
        1 -> {
            setBackgroundColor(Color.parseColor("#2BAD84"))
        }

        2 -> {
            setBackgroundColor(Color.parseColor("#FF9F18"))

        }

        3 -> {
            setBackgroundColor(Color.parseColor("#FF3B30"))

        }

        4 -> {
            setBackgroundColor(Color.parseColor("#A5A5A5"))

        }

        5 -> {
            setBackgroundColor(Color.parseColor("#5AE4D9"))

        }

        else -> {
            setBackgroundColor(Color.parseColor("#666666"))

        }
    }


}

